package com.itheima.article.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.article.pojo.ApArticleConfig;
import com.itheima.article.service.ApArticleConfigService;
import com.itheima.common.constants.BusinessConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ApArticleConfigListener {

    @Autowired
    private ApArticleConfigService apArticleConfigService;


    /**
     * 同步文章配置，上下架
     * @param msgRecord
     */
    @KafkaListener(topics = BusinessConstants.MqConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
    public void upOrDown(ConsumerRecord<String,String> msgRecord){
        //1. 获取消息信息
        String topic = msgRecord.topic();
        int partition = msgRecord.partition();
        String jsonString = msgRecord.value();
        log.info("文章上下架开始: t={},p={},msg={}",topic,partition,jsonString);
        //2. 解析json
        JSONObject jsonObject = JSON.parseObject(jsonString);
        //3. 获取文章的id
        Long articleId = jsonObject.getLong("articleId");
        //4. 获取上下架的值
        Integer enable = jsonObject.getInteger("enable");
        //5. 修改文章配置中的is_down
        LambdaUpdateWrapper<ApArticleConfig> updateWrapper = new LambdaUpdateWrapper<>();
        //eq:条件相等，set：设置。
        updateWrapper.eq(ApArticleConfig::getArticleId,articleId);
        updateWrapper.set(ApArticleConfig::getIsDown,enable);
        boolean flag = apArticleConfigService.update(updateWrapper);
        log.info("同步文章配置上下架: {}，{}，{}",articleId,enable,flag);

    }
}
